package com.shurdroides.proyectofinal.activities;

import com.shurdroides.proyectofinal.DeviceRegistrar;
import com.shurdroides.proyectofinal.R;
import com.shurdroides.proyectofinal.R.id;
import com.shurdroides.proyectofinal.R.layout;
import com.shurdroides.proyectofinal.preferences.MyPreferences;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.c2dm.C2DMessaging;

public class RegistrationUI extends Activity {

	public static final String UPDATE_UI_ACTION = "com.shurdroides.proyectofinal.UPDATE_UI";
	public static final String AUTH_PERMISSION_ACTION = "com.shurdroides.proyectofinal.AUTH_PERMISSION";

	private boolean pendingAuth = false;
	private TextView statusText;
	private EditText txtNombreUsuario;
	private ProgressBar progress;
	MyPreferences preferencias;
	Button registerButton;
	Button next;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registro_nuevo_usuario);
		preferencias = new MyPreferences(this);
		statusText = (TextView) findViewById(R.id.status);
		((Button) findViewById(R.id.register))
				.setOnClickListener(mRegisterButtonListener);
		txtNombreUsuario = (EditText) findViewById(R.id.edit_text_user_name);
		next=(Button)findViewById(R.id.btn_next_register);
		progress = (ProgressBar) findViewById(R.id.progressBar);
		Spinner accounts = (Spinner) findViewById(R.id.accounts);
		accounts.setAdapter(getGoogleAccounts(this));
		accounts.setPrompt("Select account");

		registerReceiver(mUpdateUIReceiver, new IntentFilter(UPDATE_UI_ACTION));
		registerReceiver(mAuthPermissionReceiver, new IntentFilter(
				AUTH_PERMISSION_ACTION));
		next.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		updateStatus();
	}

	@Override
	public void onDestroy() {
		unregisterReceiver(mUpdateUIReceiver);
		unregisterReceiver(mAuthPermissionReceiver);
		super.onDestroy();
	}

	private boolean updateStatus() {
		registerButton = (Button) findViewById(R.id.register);
		String deviceRegistrationID = preferencias.getDeviceRegistration();
		if (deviceRegistrationID == null) {
			statusText.setText("not registered");
			registerButton.setText("Register");
			registerButton.setClickable(true);
			progress.setVisibility(View.INVISIBLE);
			return false;
		} else {

			statusText.setText("registered");
			registerButton.setText("Unregister");
			registerButton.setClickable(true);
			progress.setVisibility(View.INVISIBLE);
			return true;
		}
	}

	private ArrayAdapter<String> getGoogleAccounts(Context context) {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		Account[] accounts = AccountManager.get(context).getAccounts();
		for (Account account : accounts) {
			if (account.type.equals("com.google")) {
				adapter.add(account.name);
			}
		}
		return adapter;
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (pendingAuth) {
			pendingAuth = false;
			String regId = C2DMessaging
					.getRegistrationId(getApplicationContext());
			if (regId != null) {
				DeviceRegistrar.registerWithServer(getApplicationContext(),
						regId);

			} else {
				C2DMessaging.register(getApplicationContext(),
						DeviceRegistrar.SENDER_ID);
			}
			statusText.setText("registering...");
			registerButton.setClickable(false);
			progress.setVisibility(View.VISIBLE);
		}
	}

	private final OnClickListener mRegisterButtonListener = new OnClickListener() {
		public void onClick(View v) {
			if (!(txtNombreUsuario.getText().length() < 3)) {

				String deviceRegistrationID = preferencias
						.getDeviceRegistration();
				if (deviceRegistrationID == null) { // register
					Spinner accounts = (Spinner) findViewById(R.id.accounts);
					preferencias.updateAccount((String) accounts
							.getSelectedItem());
					preferencias.updateName(txtNombreUsuario.getText()
							.toString());
					C2DMessaging.register(getApplicationContext(),
							DeviceRegistrar.SENDER_ID);
					statusText.setText("registering...");
					registerButton.setClickable(false);
					progress.setVisibility(View.VISIBLE);
				} else { // unregister
					C2DMessaging.unregister(getApplicationContext());
					statusText.setText("unregistering...");
					registerButton.setClickable(false);
					progress.setVisibility(View.VISIBLE);
					next.setVisibility(View.VISIBLE);
				}
			} else
				Toast.makeText(getApplicationContext(),
						"Name must be at least 3 characters long",
						Toast.LENGTH_LONG).show();
		}
	};

	private final BroadcastReceiver mUpdateUIReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {

			Log.i("reg", "---------------" + "Intent Received!");
			if (intent.getAction().equals(
					"com.google.android.c2dm.intent.REGISTRATION")) {
				Log.i("reg", "---------------" + "REGISTRO");
			} else if (intent.getAction().equals(
					"com.google.android.c2dm.intent.RECEIVE")) {
				Log.i("reg", "---------------" + "MENSAJE");
			}
			updateStatus();

		}
	};

	private final BroadcastReceiver mAuthPermissionReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle extras = intent.getBundleExtra("AccountManagerBundle");
			if (extras != null) {
				Intent authIntent = (Intent) extras
						.get(AccountManager.KEY_INTENT);
				if (authIntent != null) {
					pendingAuth = true;
					startActivity(authIntent);
				}
			}
		}
	};

}